%%%-------------------------------------------------------------------
%%% File    : p3.erl
%%% Author  : Plamen Dragozov <plamen at dragozov.com>
%%% Description : 
%%% Find the largest prime factor of a composite number.
%%% Created : 2 Dec 2008
%%%-------------------------------------------------------------------
-module(p3).

-compile(export_all).

%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
%% Function: solution(N) -> int()
%% Description: Returns the greatest prime factor of N.
%%--------------------------------------------------------------------
solution(N) ->
    next_factor(N, 2).

%%====================================================================
%% Internal functions
%%====================================================================
next_factor(0, _) -> 0;
next_factor(N, I) when I > (N div 2) ->
    N;
next_factor(N, I) ->
    case N rem I =:= 0 of
        true ->
            next_factor(N div I, I);
        _ -> next_factor(N, I + 1)
    end.
